package cc.co.cutenimy.nimyexplore.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

import cc.co.cutenimy.nimyexplore.jdbc.driver.DriverDescription;
import cc.co.cutenimy.nimyexplore.model.jdbc.ConnectionInstance;

public class CommonConnectionManager implements ConnectionManager {

	private final List<Connection> connections = new ArrayList<Connection>(8);

	public Connection get(ConnectionInstance connectionInstance,
			final DriverDescription driverDescription) throws ConnectException {
		try {
			driverDescription.loadDriverClass();
			String url = connectionInstance.getUrl();
			System.out.println("DB URL:" + url);
			Connection connection = DriverManager.getConnection(url,
					connectionInstance.getProperties());
			connections.add(connection);
			return connection;
		} catch (Exception e) {
			throw new ConnectException("Connect failed!", e);
		}
	}

	/**
	 * Close all connections. If one of the connection throw exception, this one
	 * should not terminate the clear progress\. Other connections should be
	 * closed.
	 */
	public void clear() {
		for (Connection connection : connections) {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Throwable e) {
				// TODO Log here
				e.printStackTrace();
			}
		}
		connections.clear();
	}
}
